'use client';

import { useQuery } from '@tanstack/react-query';
import {
  queryAllPostTemplate,
  queryPostTemplateStatistics,
  searchPostTemplate,
} from '@/services/api';
import type {
  IPagination,
  IPostTemplate,
  IPostTemplateStatistics,
  IQueryParams,
} from '@/interfaces';
import Box from '@/app/[locale]/admin/common/box';
import Alert from '@/app/[locale]/alert/alert';
import Spinner from '@/app/[locale]/component/spinner/spinner';
import Nodata from '@/app/[locale]/common/nodata/nodata';
import { useRouter } from 'next/navigation';
import { type ChangeEvent, useState } from 'react';
import Pagination from '@/app/[locale]/admin/common/pagination';
import type { PrefixedTTranslatedFields } from '@/lib/dictionaries';

export default function PostTemplateAdminPage(
  this: any,
  {
    source,
    translatedFields,
  }: {
    source: IPagination<IPostTemplate>;
    translatedFields: PrefixedTTranslatedFields<'postTemplateAdminPage'>;
  },
) {
  const [params, setParams] = useState<IQueryParams>({
    page: 0,
  });
  const [searchName, setSearchName] = useState('');
  const router = useRouter();

  const queryPostTemplateStatisticsQuery = useQuery(
    ['/forum', '/tags', '/statistics'],
    async () => {
      return (await queryPostTemplateStatistics()) as IPostTemplateStatistics;
    },
  );

  const queryAllPostTemplateQuery = useQuery(
    ['/forum', '/templates', params, searchName],
    async (context) => {
      if (searchName) {
        return (await searchPostTemplate({
          query: {
            ...(context.queryKey[2] as any),
            name: context.queryKey[3],
          },
        })) as IPagination<IPostTemplate>;
      } else {
        return (await queryAllPostTemplate({
          query: context.queryKey[2] as any,
        })) as IPagination<IPostTemplate>;
      }
    },
    {
      keepPreviousData: true,
      initialData: source,
    },
  );

  function onClickDetail(item: IPostTemplate) {
    router.push(`post-template/detail?id=${item.id}`);
  }

  function onClickUpdate(item: IPostTemplate) {
    router.push(`post-template/update?id=${item.id}`);
  }

  function onClickDelete(item: IPostTemplate) {
    router.push(`post-template/delete?id=${item.id}`);
  }

  function onClickPrevious() {
    const data = queryAllPostTemplateQuery.data;
    if (!data) {
      return;
    }

    const page = Math.max(0, data.pageable.page - 1);
    setParams({ ...params, page });
  }

  function onClickNext() {
    const data = queryAllPostTemplateQuery.data;
    if (!data) {
      return;
    }

    const page = Math.min(data.pageable.pages, data.pageable.page + 1);
    setParams({ ...params, page });
  }

  function onChangeSearch(e: ChangeEvent<HTMLInputElement>) {
    const value = e.target.value;
    setSearchName(value.toLowerCase());
  }

  return (
    <div className="row g-4">
      <div className="col-12">
        <Box>
          <div className="card">
            <div className="card-body">
              <h6 className="card-subtitle mb-2 text-secondary">
                {translatedFields.count.postTemplate}
              </h6>
              <h5 className="card-title">
                {queryPostTemplateStatisticsQuery.data &&
                  queryPostTemplateStatisticsQuery.data.count}

                {queryPostTemplateStatisticsQuery.isError && (
                  <Alert
                    message={queryPostTemplateStatisticsQuery.error}
                    type="error"
                  />
                )}

                {queryPostTemplateStatisticsQuery.isLoading && <Spinner />}
              </h5>
            </div>
          </div>
        </Box>
      </div>
      <div className="col">
        <Box>
          <div className="card">
            <div className="card-header bg-transparent">
              <div className="row row-cols-auto justify-content-between g-2">
                <div className="col">
                  <div className="input-group">
                    <span className="input-group-text">
                      <i className="bi bi-search"></i>
                    </span>
                    <input
                      onChange={onChangeSearch}
                      type="search"
                      className="form-control"
                      placeholder={translatedFields.tip.searchPlaceholder}
                    />
                  </div>
                </div>
                <div className="col"></div>
              </div>
            </div>
            <div className="card-body vstack gap-4">
              <div className="table-responsive">
                <table className="table table-hover align-middle">
                  <thead>
                    <tr className="text-nowrap">
                      <th scope="col" className="">
                        ID
                      </th>
                      <th scope="col" className="">
                        {translatedFields.properties.name}
                      </th>
                      <th scope="col" className="">
                        {translatedFields.properties.overview}
                      </th>
                      <th scope="col" className="">
                        {translatedFields.properties.sort}
                      </th>
                      <th scope="col" className="">
                        {translatedFields.properties.section}
                      </th>
                      <th scope="col" className=""></th>
                    </tr>
                  </thead>
                  <tbody>
                    {queryAllPostTemplateQuery.data.content.map((item) => {
                      return (
                        <tr key={item.id} className="text-nowrap">
                          <td
                            className="cursor-pointer"
                            onClick={onClickDetail.bind(this, item)}
                          >
                            {item.id}
                          </td>
                          <td
                            className="cursor-pointer"
                            onClick={onClickDetail.bind(this, item)}
                          >
                            {item.name}
                          </td>
                          <td
                            className="cursor-pointer"
                            onClick={onClickDetail.bind(this, item)}
                          >
                            {item.overview}
                          </td>
                          <td
                            className="cursor-pointer"
                            onClick={onClickDetail.bind(this, item)}
                          >
                            {item.sort}
                          </td>
                          <td
                            className="cursor-pointer"
                            onClick={onClickDetail.bind(this, item)}
                          >
                            {item.section.name}
                          </td>
                          <td>
                            <div className="hstack gap-2">
                              <button
                                onClick={onClickUpdate.bind(this, item)}
                                className="btn btn-sm btn-light"
                                type="button"
                              >
                                <i className="bi bi-pencil me-2"></i>
                                {translatedFields.operate.update}
                              </button>

                              <button
                                onClick={onClickDelete.bind(this, item)}
                                className="btn btn-sm btn-light text-danger"
                                type="button"
                              >
                                <i className="bi bi-trash me-2"></i>
                                {translatedFields.operate.delete}
                              </button>
                            </div>
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>

              {queryAllPostTemplateQuery.data.content.length === 0 && (
                <Nodata />
              )}

              <Pagination
                isShow={queryAllPostTemplateQuery.data.pageable.pages > 0}
                onPrevious={onClickPrevious}
                onNext={onClickNext}
                isPrevious={queryAllPostTemplateQuery.data.pageable.previous}
                isNext={queryAllPostTemplateQuery.data.pageable.next}
                translatedFields={translatedFields.pagination}
              />
            </div>
          </div>
        </Box>
      </div>
    </div>
  );
}
